package com.earthea.application.task;

import com.earthea.application.task.entity.Task;
import com.earthea.application.task.entity.TaskConstants;
import com.earthea.application.task.entity.TaskResult;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public abstract class AbstractTaskService<T> {
    @Autowired
    protected TaskService taskService;

    public void execute(Task task) {
        TaskResult taskResult = executeInternal(task);
        task.setStatus(taskResult.getStatus());
        task.setResult(taskResult.getDescription());
        taskService.updateTask(task);
    }

    protected abstract TaskResult executeInternal(Task task);

    public int addTask(T data) {
        return batchAddTask(Collections.singletonList(data));
    }

    public int batchAddTask(List<T> dataList) {
        if (CollectionUtils.isEmpty(dataList)) {
            return 0;
        }
        return taskService.addTask(dataList.stream().map(data -> new Task(type(), label(), data)).peek(task -> task.setMaxRetry(maxRetry())).collect(Collectors.toList()));
    }

    protected abstract String type();

    protected abstract String label();

    protected int maxRetry() {
        return TaskConstants.DEFAULT_MAX_RETRY;
    }
}
